$(function() {

// 添加的相册的路径
let imgPath = [];

// 最后的相册的id
let albumId = 6;

// 多选删除的相册id
let delAlumbList = [];

// 渲染年级列表
function drawGradeList() {
	for (let i = 0; i < mGradeList.length; i++) {
		let grade =
			`
				<div class="grade" id=${mGradeList[i].id}>
					
					<h3 class="grade-name">${mGradeList[i].gradeName}</h3>
					
					<div class="class-list">
						
					</div>
					<div class="row">
						
					</div>
					<div class="operate clearfix">
						<span class="select-all">全选<input type="checkbox" class="mselect-all"></span>
						<span class="cancel-del">取消删除</span>
						<span class="multi-del">批量删除</span>
						<div class="sort-by-time clearfix form-inline" data-toggle="tooltip" data-placement="right" title="按时间排序" id="sort">
							<span class="iconfont icon-paixu" ></span>
						</div>
					</div>
				</div>
			`;
		$(".container").append(grade);
	}
}
drawGradeList();

// 渲染班级列表
function drawClassList() {
	let Class;
	for (c of mClassList) {
		for (g of mGradeList) {
			// 判断该班属于哪个年级
			if (g.id == c.gradeId) {
				Class = `<span class="class-name" name=${c.id}>${c.className}</span>`;
				$("#" + g.id).children(".class-list").append(Class);
				break;
			}
		}
	}
	Class = "";
}
drawClassList();

// 渲染每个班的相册集
function drawAlbumList(gradeId, classId) {
	// 渲染前清空多选状态
	clearMultiDel();
	// 渲染前清空当前年级下的其他班相册
	$("#" + gradeId).find(".img-list-con").remove();

	let album, className, img;
	className = $("span[name=" + classId + "]").text();

	let flag = false;
	for (a of mAlbumList) {
		if (classId == a.classId) {
			flag = true;
			if (a.photos.length >= 4) {
				album =
					`
						<div class="col-lg-4 col-md-4 col-sm-6  col-xs-6 img-list-con" name=${a.id}>
							<div class="img-list" name="${a.classId}">
								<div class="top">
									<img src=${a.photos[0]} class="img-responsive img-rounded">
									<div class="desc-img">
										<!-- 图片数量 -->
										<span class="iconfont icon-tupian"></span>
										<span class="num">${a.photos.length}</span>
										<!-- 删除 -->
										<div class="del" title="删除">
											<span class="iconfont icon-shanchu"></span>
										</div>
									</div>
								</div>
								<div class="bottom clearfix">
									<div class="bottom-img"><img src=${a.photos[1]}></div>
									<div class="bottom-img"><img src=${a.photos[2]}></div>
									<div class="bottom-img"><img src=${a.photos[3]}></div>
								</div>
								<div class="upload-time text-info">
									<div class="multi-select">
										<input type="checkbox" value=${a.id}>
									</div>
									${a.uploadTime}
								</div>
								
							</div>
						</div>
					`;
			}
			if (a.photos.length == 3) {
				album =
					`
						<div class="col-lg-4 col-md-4 col-sm-6  col-xs-6 img-list-con" name=${a.id}>
							<div class="img-list" name="${a.classId}">
								<div class="top">
									<img src=${a.photos[0]} class="img-responsive img-rounded">
									<div class="desc-img">
										<!-- 图片数量 -->
										<span class="iconfont icon-tupian"></span>
										<span class="num">${a.photos.length}</span>
										<!-- 删除 -->
										<div class="del" title="删除">
											<span class="iconfont icon-shanchu"></span>
										</div>
									</div>
								</div>
								<div class="bottom clearfix">
									<div class="bottom-img"><img src=${a.photos[1]}></div>
									<div class="bottom-img"><img src=${a.photos[2]}></div>
								</div>
								<div class="upload-time text-info">
									<div class="multi-select">
										<input type="checkbox" value=${a.id}>
									</div>
									${a.uploadTime}
								</div>
							</div>
						</div>
					`;
			}
			if (a.photos.length == 2) {
				album =
					`
						<div class="col-lg-4 col-md-4 col-sm-6  col-xs-6 img-list-con" name=${a.id}>
							<div class="img-list" name="${a.classId}">
								<div class="top">
									<img src=${a.photos[0]} class="img-responsive img-rounded">
									<div class="desc-img">
										<!-- 图片数量 -->
										<span class="iconfont icon-tupian"></span>
										<span class="num">${a.photos.length}</span>
										<!-- 删除 -->
										<div class="del" title="删除">
											<span class="iconfont icon-shanchu"></span>
										</div>
									</div>
								</div>
								<div class="bottom clearfix">
									<div class="bottom-img"><img src=${a.photos[1]}></div>
								</div>
								<div class="upload-time text-info">
									<div class="multi-select">
										<input type="checkbox" value=${a.id}>
									</div>
									${a.uploadTime}
								</div>
							</div>
						</div>
					`;
			}
			if (a.photos.length == 1) {
				album =
					`
						<div class="col-lg-4 col-md-4 col-sm-6  col-xs-6 img-list-con" name=${a.id}>
							<div class="img-list" name="${a.classId}">
								<div class="top">
									<img src=${a.photos[0]} class="img-responsive img-rounded">
									<div class="desc-img">
										<!-- 图片数量 -->
										<span class="iconfont icon-tupian"></span>
										<span class="num">${a.photos.length}</span>
										<!-- 删除 -->
										<div class="del" title="删除">
											<span class="iconfont icon-shanchu"></span>
										</div>
									</div>
								</div>
								<div class="bottom clearfix">
									
								</div>
								<div class="upload-time text-info">
									<div class="multi-select">
										<input type="checkbox" value=${a.id}>
									</div>
									${a.uploadTime}
								</div>
							</div>
						</div>
					`;
			}
			$("#" + gradeId).children(".row").append(album);
		}
	}
	// 对当前没有相片的处理
	if (!flag) {
		$("#" + gradeId).find(".multi-del").css({
			"display":"none"
		})
		$("#" + gradeId).find(".no-album").remove();
		$("#" + gradeId).find("#sort").css("display","none");
		
		let h3 = "<h3 class=\"no-album\">暂时没有相册哦！</h3>"
		$("#" + gradeId).children(".row").append(h3);
	} else {
		$("#" + gradeId).find(".multi-del").css({
			"display":"inline-block"
		})
		$("#" + gradeId).find(".no-album").remove();
		$("#" + gradeId).find("#sort").css("display","inline");
	}
	album = "";
}

// 初始化相册
function initAlbum() {
	//小班第一个相册
	let smallFirst = $("#1").find(".class-name").attr("name");
	let middleFirst = $("#2").find(".class-name").attr("name");
	let bigFirst = $("#3").find(".class-name").attr("name");
	
	$("#1").find(".class-name[name="+smallFirst+"]").addClass('active');
	$("#2").find(".class-name[name="+middleFirst+"]").addClass('active');
	$("#3").find(".class-name[name="+bigFirst+"]").addClass('active');
	
	drawAlbumList(1, smallFirst);
	drawAlbumList(2, middleFirst);
	drawAlbumList(3, bigFirst);
}
initAlbum();

// 点击班名获取相册
$(".container").on('click', '.class-name', function() {
	$(this).parents(".grade").find(".class-name").removeClass("active");
	$(this).addClass("active");
	let currentClass = $(this).attr("name");
	let currentGrade = $(this).parents(".grade").attr("id");
	console.log(currentGrade, currentClass);
	drawAlbumList(currentGrade, currentClass);
})

//删除相册
$(".container").on('click', '.del', delImgList);

function delImgList(e) {
	e.stopPropagation();
	let that = $(this);
	swal({
		title: "您确定要删除该相册吗",
		text: "删除后将无法恢复，请谨慎操作！",
		type: "warning",
		showCancelButton: true,
		confirmButtonColor: "#DD6B55",
		confirmButtonText: "是的，我要删除！",
		cancelButtonText: "让我再考虑一下…",
		closeOnConfirm: false,
	}, function(isConfirm) {
		if (isConfirm) {
			// 获取删除的相册的年级和班，删除后便于重新渲染
			let gradeId, classId;
			gradeId = that.parents(".grade").attr("id");
			classId = that.parents(".img-list").attr("name");
			let Aid = parseInt(that.parents(".img-list-con").attr("name"));
			for (let i = 0; i < mAlbumList.length; i++) {
				if (mAlbumList[i].id == Aid) {
					mAlbumList.splice(i, 1);
					break;
				}
			}
			drawAlbumList(gradeId, classId);
			swal({
				title: "删除成功！",
				text: "您已经永久删除了这册相册",
				type: "success"
			})
		}
	})
}

// 工具提示
$('[data-toggle="tooltip"]').tooltip();

// 添加相册
// 渲染可选择的年级
function setGrade() {
	for (let i = 0; i < mGradeList.length; i++) {
		let option = ` <option value=${mGradeList[i].id}>${mGradeList[i].gradeName}</option> `;
		$(".m-grade-class").append(option);
	}
}
setGrade();

// 渲染可选择的班级
$(".m-grade-class").on("change", function() {
	$(".m-grade option").remove();
	let first = `<option value ="请选择">请选择</option>`;
	$(".m-grade").append(first);
	let gradeId = $(this).val();
	for (c of mClassList) {
		if (c.gradeId == gradeId) {
			let option = ` <option value=${c.id}>${c.className}</option> `;
			$(".m-grade").append(option);
		}
	}
})

// 预览图片
$(".select-img").on('change', function(fileDom) {
	let reader;
	//判断是否支持FileReader
	if (window.FileReader) {
		reader = new FileReader();
	} else {
		alert("您的设备不支持图片预览功能，如需该功能请升级您的设备！");
	}
	let file = $(this)[0].files[0];
	let imageType = /^image\//;
	if (!imageType.test(file.type)) {
		alert("请选择图片！");
		return;
	}
	reader.onload = function(e) {
		let img =
			`
					<div class="add-img-con col-lg-3 col-md-3 col-sm-6 col-xs-12">
						<img src=${e.target.result} class="img-responsive">
						<span class="iconfont icon-shanchu del-pre"></span>
					</div>
				`;
		imgPath.push(e.target.result);
		$(".preview-img").append(img);
	}
	reader.readAsDataURL(file);
	console.log(imgPath);
})

// 提交验证
/**
 * @param {String} grade 年级
 * @param {String} Class 班级
 * @param {Array} imgPath 图片路径
 * @param {String} desc 描述
 */
function volidate(grade, Class, imgPath) {
	if (grade == "请选择" || Class == "请选择" || imgPath.length == 0) {
		return false;
	} else {
		return true;
	}
}

// 提交
$(".btn-add").on("click", add);
function add() {
	let gradeId = $(".m-grade-class").val();
	let Class = $(".m-grade").val();
	let desc = $(".add-desc").val();
	if(desc.trim().length == 0){
		desc = "暂无描述"
	}
	let title = $(".add-title").val();
	if(title.trim().length == 0){
		title = "暂无标题"
	}
	let currentDate = getCurrentDate();
	
	let flag = volidate(gradeId, Class, imgPath);
	
	if (!flag) {
		swal("未选择班级或图片！")
		// 提示添加失败
		return;
	}

	let album = {
		id:++albumId,
		photos:imgPath,
		title:title,
		detail:desc,
		uploadTime:currentDate,
		classId:parseInt(Class)
	};
	mAlbumList.push(album);
	
	drawAlbumList(gradeId,Class);
	$('#add-img-list').modal('hide')
	swal({
		title: "添加成功!",
		type: "success"
	})
	setTimeout(function() {
		clearAddInfo();
	}, 500);
}

// 关闭
$(".close-add").on('click', function() {
	$('#add-img-list').modal('hide')
	clearAddInfo();
})
// 清空添加信息
function clearAddInfo() {
	$(".m-grade-class").val("请选择");
	$(".m-grade").val("请选择");
	$(".add-desc").val("");
	$(".add-img-con").remove();
	imgPath = [];
	$(".add-title").val("");
}

// 删除预览的图片
$(".container").on('click', ".del-pre", delPreview);

function delPreview() {
	console.log('err');
	curImg = $(this).siblings("img").attr("src");
	for (let i = 0; i < imgPath.length; i++) {
		if (curImg == imgPath[i])
			imgPath.splice(i, 1);
	}
	$(this).parents(".add-img-con").remove();
}

// 获取当前日期
function getCurrentDate() {
	let date, year, month, day;
	date = new Date();
	year = date.getFullYear();
	month = date.getMonth()+1;
	day = date.getDate();
	return year + '.' + month + '.' + day;
}

//批量删除
$(".container").on("click",'.multi-del',function(){
	$(".multi-select").css({
		"display":"none"
	})
	$(".select-all").css({
		"display":"none"
	})
	$(".cancel-del").css({
		"display":"none"
	})
	delAlumbList = [];
	
	if(delAlumbList.length==0){
		$(this).parents(".grade").find(".multi-select").css({
			"display":"block"
		})
		$(this).parents(".grade").find(".select-all").css({
			"display":"inline-block"
		})
		$(this).parents(".grade").find(".cancel-del").css({
			"display":"inline-block"
		})
		$(this).removeClass("multi-del");
		$(this).addClass("confirm-del");
	}
})
// 全选
$(".container").on('change','.mselect-all',selectAll);

function selectAll(){
	
	if($(this).is(":checked")){
		$(this).parents(".grade").find(".multi-select input").prop("checked",true);
		$(this).parents(".grade").find(".multi-select input").each(function(){
			delAlumbList.push($(this).val());
		})
	}else{
		$(this).parents(".grade").find(".multi-select input").prop("checked",false);
		delAlumbList = [];
	}
}

// 单个checkbox的选中事件
$(".container").on('change','.multi-select input',function(){
	
	if($(this).is(":checked")){
		// 判断已加入的项
		for(let i=0;i<delAlumbList.length;i++){
			if(delAlumbList[i] == $(this).val()){
				return;
			}
		}	
		delAlumbList.push($(this).val());
	}else{
		for(let i=0;i<delAlumbList.length;i++){
			if(delAlumbList[i] == $(this).val()){
				delAlumbList.splice(i,1);
				break;
			}
		}
	}
	console.table(delAlumbList);
	
	let allOptions = $(this).parents(".grade").find(".multi-select input").length;
	
	let selectAll = $(this).parents(".grade").find(".mselect-all");
	
	
	if(delAlumbList.length<allOptions){
		selectAll.prop("checked",false);
	}else{
		selectAll.prop("checked",true);
	}
	
})

// 批量删除事件
$(".container").on('click','.confirm-del',confirmDel);
function confirmDel(){
	swal({
		title: "您确定要删除该相册吗",
		text: "删除后将无法恢复，请谨慎操作！",
		type: "warning",
		showCancelButton: true,
		confirmButtonColor: "#DD6B55",
		confirmButtonText: "是的，我要删除！",
		cancelButtonText: "让我再考虑一下…",
		closeOnConfirm: false,
	}, function(isConfirm) {
		if (isConfirm) {
			
			if(delAlumbList.length==0){
				swal("您还没有选择相册!");
				return false;
			}
			
			let gradeId,classId;
			for(let i=delAlumbList.length-1;i>=0;i--){
				for(let j=mAlbumList.length-1;j>=0;j--){
					if(delAlumbList[i] == mAlbumList[j].id){
						
						
						classId = mAlbumList[j].classId;
						for(c of mClassList){
							if(c.id == classId){
								gradeId = c.gradeId;
								break;
							}
						}
						
						delAlumbList.splice(i,1);
						mAlbumList.splice(j,1);
						
						break;
					}
				}
			}
			drawAlbumList(gradeId,classId);
			swal({
				title: "删除成功！",
				text: "您已经永久删除了这册相册",
				type: "success"
			})
			clearMultiDel();
		}
	})
}

// 取消删除
$(".container").on('click','.cancel-del',clearMultiDel);
// 批量删除的结尾
function clearMultiDel(){
	// 移除相关节点
	$(".multi-select").css({
		"display":"none"
	})
	$(".select-all").css({
		"display":"none"
	})
	$(".cancel-del").css({
		"display":"none"
	})
	// 清空删除列表
	delAlumbList = [];
	
	// 清空全选选择状态
	$(".mselect-all").prop("checked",false);
	
	// 清空每一项的选择状态
	$(this).parents(".grade").find(".multi-select input").prop("checked",false);
	
	// 恢复节点
	$(".confirm-del").addClass("multi-del");
	$(".confirm-del").removeClass("confirm-del");
}


// 回到顶部
let stop;
$(".back-top").click(function(){
	let scrollHeight = document.body.scrollTop | document.documentElement.scrollTop;
	stop = setInterval(backTop,20);
});
function backTop(){
	let scrollHeight = document.body.scrollTop | document.documentElement.scrollTop;
	scrollHeight-=50;
	if(scrollHeight <= 0){
		console.log('err');
		clearInterval(stop);
		return;
	}
	window.scrollTo(0,scrollHeight);
}

// 按时间排序

// 比较时间大小
function compareDate(date1,date2){
	let d1,d2,da1,da2;
	da1 = da2 = "";
	d1 = date1.split('.');
	d2 = date2.split('.');
	
	for(let i=0;i<d1.length;i++){
		if(d1[i]<10) d1[i] = '0' + d1[i];
		da1 += d1[i];
	}
	for(let i=0;i<d2.length;i++){
		if(d2[i]<10) d2[i] = '0' + d2[i];
		da2 += d2[i];
	}
	if(da1>da2){
		return true;
	}else{
		return false;
	}

}

// 把相册按时间排序
function sortAlbumByTime(){
	for(let i=0;i<mAlbumList.length-1;i++){
		for(let j=0;j<mAlbumList.length-i-1;j++){
			console.log(i);
			if(compareDate(mAlbumList[j].uploadTime,mAlbumList[j+1].uploadTime)){
				// 大于交换
				let tmp = mAlbumList[j];
				mAlbumList[j] = mAlbumList[j+1];
				mAlbumList[j+1] = tmp;
			}
		}
	}		
}

let flag = true;	//排序的标志
$(".container").on("click","#sort",function(){
	let gradeId,classId;
	gradeId = $(this).parents(".grade").attr('id');
	classId = $(this).parents('.grade').find('.img-list').attr('name');
	sortAlbumByTime();
	// console.table(mAlbumList);
	if(flag){
		mAlbumList.reverse();
	}
	flag = !flag;
	console.table(mAlbumList);
	drawAlbumList(gradeId,classId);
})

// 点击相册跳转页面
$(".container").on('click','.img-list-con',function(){
	let albumId = $(this).attr('name');
	localStorage.setItem("albumId",albumId);
	location.href = "../pages/photoWallDetail.html";
})
})
